/**
 * 
 */
package com.fita.admin.security;

import com.fita.admin.entity.security.Login;
import com.fita.admin.service.authority.PrincipalService;
import com.fita.admin.service.authority.ResourceService;
import com.fita.entity.principal.Principal;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;
import java.util.Map;


/**
 * @author downpour
 */
public class ApplicationAuthenticationProvider implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationAuthenticationProvider.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private ResourceService resourceService;
    
    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        // ======= initialize other user properties =======
        Principal principal = principalService.loadByName(username);
        
        if(principal == null) {
            throw new UsernameNotFoundException("未能找到用户");
        }

        logger.info("ApplicationAuthenticationProvider#loadUserByUsername() - principal [" + principal.getUsername() + "] is found to login. ");
        
        // 1. construct Login by Principal
        Login login = new Login(principal);
        
        if(principal.getDistrict() != null && (StringUtils.equals(principal.getAuthority(), "SALE_DIRECTOR") || StringUtils.equals(principal.getAuthority(), "SALE_USER"))) {
            login.initilization(principal.getDistrict());
        }
        
        // 2. initialize role based resources
        Map<String, List<String>> resources= resourceService.list(principal);
        if(MapUtils.isNotEmpty(resources)) {
            login.initResources(resources);
        }
        
        return login;
        
    }

}
